<template>
  <div class="login background-image">
    <a-form :model="form" :rules="rules" @submit="onFinish" class="login-form">
      <h2>登录</h2>
      <a-form-item name="username" :rules="[{ required: true, message: '请输入用户名' }]">
        <a-input v-model:value="form.username" placeholder="用户名" />
      </a-form-item>
      <a-form-item name="password" :rules="[{ required: true, message: '请输入密码' }]">
        <a-input-password v-model:value="form.password" placeholder="密码" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" class="login-form-button">
          登录
        </a-button>
      </a-form-item>
      <a-alert v-if="errorMessage" message="登录失败" description="请检查用户名和密码" type="error" show-icon />
    </a-form>
  </div>
</template>

<script>
import axios from 'axios';

import { Form, Input, Button, Alert, InputPassword } from 'ant-design-vue';

export default {
  name: 'Login',
  components: {
    'a-form': Form,
    'a-form-item': Form.Item,
    'a-input': Input,
    'a-button': Button,
    'a-alert': Alert,
    'a-input-password': InputPassword
  },
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      errorMessage: ''
    };
  },
  computed: {
    rules() {
      return {
        username: [ { required: true, message: '请输入用户名', trigger: 'blur' } ],
        password: [ { required: true, message: '请输入密码', trigger: 'blur' } ]
      };
    }
  },
  methods: {
    async onFinish() {
      try {
        const response = await axios.post('http://localhost:5000/login', this.form);
        localStorage.setItem('token', response.data.access_token);
        this.$router.push('/dashboard');
        this.errorMessage = '';
      } catch (error) {
        this.errorMessage = '登录失败';
        console.error('登录失败', error);
      }
    }
  }
};
</script>

<style scoped>
.background-image {
  background-image: url(@/assets/tech_background.jpg);
  background-size: 100% auto;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  min-height: 100vh;
}
.login {
  max-width: 300px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
input {
  border-radius: 20px;
  width: 100%;
  margin-bottom: 10px;
  padding: 8px;
  border: none;
}
button {
  width: 100%;
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
button:hover {
  background-color: #45a049;
}

.error-message-red {
  color: red;
}
</style>